<template>
    <div>
        <!-- 页面头部导航 -->
        <el-page-header
            content="个人中心"
            icon=""
            title="企业门户网站管理系统"
        />

        <!-- 用户信息展示区域 -->
        <el-row
            :gutter="20"
            class="el-row"
        >
            <!-- 右侧表单区域 -->
            <el-col :span="16"> <!-- 移除头像后占满整行 -->
                <el-card>
                    <template #header>
                        <div class="card-header">
                            <span>个人信息</span>
                        </div>
                    </template>

                    <!-- 用户信息表单 -->
                    <el-form
                        ref="userFormRef"
                        :model="userForm"
                        :rules="userFormRules"
                        label-width="120px"
                        class="demo-ruleForm"
                    >
                        <el-form-item
                            label="用户名"
                            prop="username"
                        >
                            <el-input v-model="userForm.username" />
                        </el-form-item>
                        
                        <!-- 密码修改入口 -->
                        <el-form-item
                            label="密码"
                        >
                            <el-link type="primary" @click="handelPassword">点击修改</el-link>
                        </el-form-item>

                        <!-- 提交按钮 -->
                        <el-form-item>
                            <el-button
                                type="primary"
                                @click="submitForm()"
                            >更新</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-col>
        </el-row>

        <!-- 修改密码弹窗 -->
        <el-dialog v-model="dialogVisible" title="修改密码" width="50%">
            <el-form :rules="pswRules">  <!-- 验证规则 -->
                <el-form-item
                    label="旧密码"
                    prop="oldPassword"
                >
                    <el-input
                        v-model="oldPassword"
                        type="password"
                    />
                </el-form-item>
                
                <el-form-item
                    label="新密码"
                    prop="newPassword"
                >
                    <el-input
                        v-model="newPassword"
                        type="password"
                    />
                </el-form-item>
                
                <el-form-item
                    label="再次输入新密码"
                    prop="newPasswordAgain"
                >
                    <el-input
                        v-model="newPasswordAgain"
                        type="password"
                    />
                </el-form-item>
                
                <el-form-item>
                    <el-button
                        type="primary"
                        @click="submitPassword()"
                    >提交</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script setup>
// 导入Vuex状态管理
import { useStore } from "vuex";
// 导入Vue组合式API
import {  ref, reactive } from "vue";

// 导入HTTP请求工具
import axios from 'axios'
// 导入Element Plus消息提示组件
import { ElMessage } from "element-plus";

// 获取Vuex存储实例
const store = useStore();

// 密码修改弹窗显示控制
let dialogVisible = ref(false)

// 从Vuex中获取用户信息初始值（
let { username,  password, role, id } = store.state.userInfo;

// 表单引用和数据模型
const userFormRef = ref();
let userForm = reactive({
  username,
  password,
  role,
  id
});

// 密码修改表单数据
let oldPassword = ref('')
let newPassword = ref('')
let newPasswordAgain = ref('')


// 密码修改表单验证规则
const pswRules = reactive({
  oldPassword: [{ message: "请输入旧密码", trigger: "blur" }],
  newPassword: [{ message: "请选择新密码", trigger: "blur" }],
  newPasswordAgain: [{ message: "请输入新密码", trigger: "blur" }]
});


/**
 * 更新用户信息
 * 1. 验证表单数据
 * 2. 发送更新请求
 * 3. 更新Vuex中的用户信息
 * 4. 显示操作结果
 */
const submitForm = () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      // 提交表单数据到服务器
      const res = await axios.patch("/user/updateById", userForm)
      
      if (res.data.code === 0) {
        // 更新成功，重新获取用户信息并更新Vuex
        const userInfo = await axios.get(`/user/findByUsername?username=${userForm.username}`)
        store.commit("changeUserInfo", userInfo.data.data)
        ElMessage.success("信息更新成功")
      } else if (res.data.code === 1) {
        // 用户名已存在
        ElMessage.error("该用户名已存在")
      }
    }
  })
}

/**
 * 打开密码修改弹窗
 */
const handelPassword = async () => {
  dialogVisible.value = true
}

/**
 * 提交密码修改
 * 1. 验证新旧密码是否符合要求
 * 2. 发送密码修改请求
 * 3. 更新Vuex中的用户信息
 * 4. 关闭弹窗并显示结果
 */
const submitPassword = async () => {
  // 验证表单是否填写完整
  if (newPassword.value === '' || oldPassword.value === '' || newPasswordAgain.value === '') {
    ElMessage.error("尚未完成填写")
  } else {
    // 验证密码逻辑
    if (newPassword.value === oldPassword.value) {
      ElMessage.error("新旧密码相同")
    } else if (newPassword.value !== newPasswordAgain.value) {
      ElMessage.error("两次输入新密码不一致")
    } else if (newPassword.value === newPasswordAgain.value) {
      // 验证旧密码是否正确
      if (oldPassword.value === store.state.userInfo.password) {
        // 提交密码修改请求
        await axios.patch(`/user/updatePassword?id=${store.state.userInfo.id}&password=${newPassword.value}`)
        
        // 更新用户信息
        const newInfo = await axios.get(`/user/findByUsername?username=${userForm.username}`)
        store.commit("changeUserInfo", newInfo.data.data)
        
        // 重置表单并关闭弹窗
        ElMessage.success("密码已更新")
        newPassword.value = ''
        newPasswordAgain.value = ''
        oldPassword.value = ''
        dialogVisible.value = false
      } else {
        ElMessage.error("旧密码错误")
      }
    }
  }
}
</script>

<style scoped lang="scss">
.el-row {
  margin-top: 20px;
}
.el-link {
  margin-right: 8px;
}
.el-link .el-icon--right.el-icon {
  vertical-align: text-bottom;
}
</style>